<template>
    <el-button type="primary" :icon="FolderOpened" @click="goDialogVisible">导入设备与户表对应关系数据</el-button>

    <el-dialog
      title="导入数据"
      v-model="dialogVisible"
      width="30%"
      :before-close="handleClose"
      :destroy-on-close="true"
    >
      <el-upload
        ref="upload"
        class="upload-demo"
        accept=".xlsx,.xls,.csv"
        action="/system/user/importData"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :file-list="fileList"
        :auto-upload="false"
        :http-request="handleTestSuccess"
        :on-change="handleChange"
        @submit="onSubmit"
      >
        <el-button size="small" type="primary" :disabled="!props.districtId">选取文件</el-button>
        <div class="el-upload__tip">仅支持上传.xlsx/.xls/.csv格式的文件</div>
      </el-upload>

      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>

        <el-button type="primary" :disabled="!props.districtId" :loading="loading" @click="onSubmit"
          >确认导入</el-button
        >
      </span>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref, defineProps } from 'vue';
import { ElMessage } from "element-plus"
import { FolderOpened } from '@element-plus/icons-vue';

const emits = defineEmits(["importData"])
const dialogVisible = ref(false)
const fileList = ref([])
const loading = ref(false)
const handleClose = () => {
  loading.value = false
  fileList.value = []
  dialogVisible.value = false
}
const props = defineProps(['districtId']);
const findDistrictId = () => {
  if(!props.districtId) {
    ElMessage({
      message: "请先选择台区",
      type: "error",
      duration: 2 * 1000
    })
  }else {
    dialogVisible.value = true;
  }
}
// 去导入数据
const goDialogVisible = () => {
  findDistrictId();
}
// 提交数据
const onSubmit = () => {
  if (!fileList.value.length) {
    ElMessage({
      message: "请选择要导入的文件",
      type: "error",
      duration: 2 * 1000
    })
    return
  }
  handleTestSuccess()
}
// 验证文件
const handleTestSuccess = () => {
  loading.value = true
  const fileFormData = new FormData()
  const newFileList = fileList.value.map((i: any) => i.raw)
  newFileList.map((item) => {
    fileFormData.append("districtId", props.districtId)
    fileFormData.append("file", item)
  })
  emits("importData", fileFormData, () => {
    loading.value = false
  })
}
// 选择文件
const handleChange = (_: any, data2: any) => {
  fileList.value = data2
}
// 删除文件
const handleRemove = (_: any, fileList: any) => {
  fileList.value = fileList
}
// 预览文件
const handlePreview = (file: any) => {
  console.log(file)
}
// 上传成功时的回调函数
const importReuslt = () => {
  loading.value = false
}
defineExpose({
  importReuslt,
  handleClose
})
</script>

<style scoped lang="less">
:deep(.el-upload--text) {
  width: auto;
  height: 34px;
  border: 0px dashed #d9d9d9;
  text-align: left;

}
</style>
